package udp_tcp;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TCPClient {
    public static void main(String[] args) {
        // 服务器地址和端口
        String serverHost = "localhost";
        int serverPort = 12345;

        try (Socket socket = new Socket(serverHost, serverPort);
             Scanner scanner = new Scanner(System.in)) {

            System.out.println("已连接到服务器: " + socket.getRemoteSocketAddress());

            // 获取输入流和输出流
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));

            // 发送消息
            System.out.print("请输入要发送的消息: ");
            String message = scanner.nextLine();
            out.println(message);
            System.out.println("已发送消息: " + message);

            // 接收响应
            String response = in.readLine();
            System.out.println("服务器响应: " + response);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}